from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from chaojiying import Chaojiying  # 导入接码
from selenium.common.exceptions import TimeoutException
import logging  # 日志记录
import time  # 导入时间
from selenium.webdriver.common.action_chains import ActionChains  # 导入动作链
from io import BytesIO  # 用于二进制的读写


logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')

username = 'Cthousand'  # 用户名
password = input('password:')  # 密码
soft_id = '931779'  # 软件ID
captcha_kind = '9101'  # 验证码类型

client = Chaojiying(username=username, password=password,
                    soft_id=soft_id)  # 创建一个接码实例
browser = webdriver.Chrome()  # 实例化浏览器


def get_position(captcha_result):
    '''
    提取接码平台返回的坐标
    '''
    captcha1 = captcha_result['pic_str'].split(',')
    x = captcha1[0]
    y = captcha1[1]
    logging.info(f'坐标：{(x, y)}')
    return int(x)


def login():  # 登录
    browser.get('https://captcha1.scrape.center/')  # 向服务器发送url请求
    time.sleep(1)
    browser.find_element(
        by=By.CSS_SELECTOR, value='input[type="text"]').send_keys('admin')  # 用户名输入
    browser.find_element(
        by=By.CSS_SELECTOR, value='input[type="password"]').send_keys('admin')  # 密码输入
    # 点击点击时灵时不灵，可能是网站的问题
    for i in range(100):
        try:
            login = browser.find_element(by=By.XPATH,
                                         value='//span[contains(text(),"登录")]')
            print(login.text)
            login.click()
            time.sleep(1)  # 没隔一秒点击一次登录
        except:
            break  # 如果找不到登录元素就跳出循环
    try:
        WebDriverWait(browser, 10).until(EC.presence_of_element_located(
            (By.XPATH, '//div[@class="geetest_panel_next"]/div[1]')))  # 等待页面加载
    except:
        logging.error('超时！')
    captcha = browser.find_element(
        by=By.CSS_SELECTOR, value='canvas[class~="geetest_canvas_slice"]')  # 定位到验证码图片
    captcha_png_ba64 = captcha.screenshot_as_png  # 获取截图二进制

    logging.info(f'发送验证码中..')

    captcha_result = client.post_pic(captcha_png_ba64,  # 向接码平台发送验证码和图片类型
                                     captcha_kind)
    logging.info(f'captcha:{captcha_result}')  # 输出接码结果
    x = get_position(captcha_result)  # 获取偏移量坐标
    slider = browser.find_element(
        by=By.CSS_SELECTOR, value='div.geetest_ready div.geetest_slider_button')  # 找到滑块元素
    ActionChains(browser).click_and_hold(slider).perform()    # 一键三连，hold+移动+释放
    ActionChains(browser).move_by_offset(x, 0).perform()
    ActionChains(browser).release().perform()
    try:  # 验证是否成功登录
        WebDriverWait(browser, 10).until(EC.presence_of_element_located(
            (By.XPATH, '//h2[contains(text(), "登录成功")]')))
        client.report_error(captcha_result['pic_id'])  # 上传错误验证码图片id给接码平台
        # browser.close()
        logging.info('登录成功！')
    except TimeoutException:
        logging.error('登录失败')
    time.sleep(5)
    browser.close()  # 记得关浏览器


if __name__ == '__main__':
    login()
